<template>
  <div class="department-container">
    <a-card class="general-card" title="部门管理">
      <!-- 工具栏 -->
      <template #extra>
        <a-button type="primary" @click="openAddDialog">
          <template #icon>
            <icon-plus />
          </template>
          新增部门
        </a-button>
      </template>

      <!-- 数据表格 -->
      <a-table
        :loading="loading"
        :columns="columns"
        :data="data"
        :pagination="false"
        row-key="id"
      >
        <template #createTime="{ record }">
          {{ formatDate(record.createTime) }}
        </template>
        <template #updateTime="{ record }">
          {{ formatDate(record.updateTime) }}
        </template>
        <template #operations="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleEdit(record)">
              <template #icon><icon-edit /></template>
              编辑
            </a-button>
            <a-popconfirm
              content="确定要删除这个部门吗？"
              @ok="handleDelete(record)"
            >
              <a-button type="text" size="small" status="danger">
                <template #icon><icon-delete /></template>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑对话框 -->
    <a-modal
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      @ok="handleSubmit"
      @cancel="closeDialog"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <a-form-item field="name" label="部门名称" validate-trigger="blur">
          <a-input v-model="formData.name" placeholder="请输入部门名称" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import type { TableColumnData } from '@arco-design/web-vue'
import type { DeptItem } from '@/apis/system/dept'
import { addDept, deleteDept, getDeptList, updateDept } from '@/apis/system/dept'

// 表格列定义
const columns: TableColumnData[] = [
  { title: '部门名称', dataIndex: 'name' },
  { title: '创建时间', dataIndex: 'createTime', slotName: 'createTime' },
  { title: '更新时间', dataIndex: 'updateTime', slotName: 'updateTime' },
  { title: '操作', slotName: 'operations', width: 160, fixed: 'right' }
]

// 表格数据和加载状态
const data = ref<DeptItem[]>([])
const loading = ref(false)

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const formData = ref({
  id: undefined as number | undefined,
  name: ''
})
const rules = {
  name: [{ required: true, message: '请输入部门名称' }]
}

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 获取部门列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getDeptList()
    if (res.code === 1) {
      data.value = res.data
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 打开新增对话框
const openAddDialog = () => {
  dialogTitle.value = '新增部门'
  formData.value = { id: undefined, name: '' }
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (record: DeptItem) => {
  dialogTitle.value = '编辑部门'
  formData.value = { ...record }
  dialogVisible.value = true
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  await formRef.value?.validate()

  const { id, name } = formData.value
  try {
    if (id) {
      // 编辑
      const res = await updateDept({ id, name })
      if (res.code === 1) {
        Message.success('修改成功')
        closeDialog()
        fetchData()
      }
    } else {
      // 新增
      const res = await addDept({ name })
      if (res.code === 1) {
        Message.success('添加成功')
        closeDialog()
        fetchData()
      }
    }
  } catch (error) {
    console.error('保存失败:', error)
  }
}

// 删除部门
const handleDelete = async (record: DeptItem) => {
  try {
    const res = await deleteDept(record.id)
    if (res.code === 1) {
      Message.success('删除成功')
      fetchData()
    }
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="less">
.department-container {
  padding: 20px;
}
</style>
